<?php
/**
 * Route class file.
 *
 * @author         RcPHP Dev Team
 * @copyright      Copyright (c) 2013,RcPHP Dev Team
 * @license        Apache License 2.0 {@link http://www.apache.org/licenses/LICENSE-2.0}
 * @package        Core
 * @since          1.0
 */
namespace RCPHP;

use RCPHP\Util\Check;

defined('IN_RCPHP') or exit('Access denied');

class Route
{

	/**
	 * Route dispatch
	 *
	 * @return void
	 */
	public static function dispatch()
	{
		if(Check::isClient())
		{
			// 客户端路由处理
			self::client();
		}
		else
		{
			// 服务端路由处理 兼容格式
			self::server();
		}
	}

	/**
	 * Route for server.
	 *
	 * @return void
	 */
	private static function server()
	{
		if(!empty($_SERVER['PATH_INFO']))
		{
			$reqStr = str_replace(URL_PATHINFO_EXT, "", trim(Request::header("PATH_INFO"), "/"));
			$reqStr = URL_PATHINFO_DEPR != '/' ? str_replace(URL_PATHINFO_DEPR, "/", $reqStr) : $reqStr;

			/**
			 * 优先使用自定义路由
			 */
			if(defined("URL_CUSTOM_ROUTE") && URL_CUSTOM_ROUTE === true)
			{
				/**
				 * 支持
				 * int
				 * string
				 * all
				 */
				$conf = RcPHP::getConfig("route");

				if(!empty($conf) && is_array($conf))
				{
					foreach($conf as $key => $value)
					{
						$key = str_replace(array(
							':all',
							':int',
							':string'
						), array(
							'.+?',
							'[\d]+',
							'[\D]+'
						), $key);

						if(preg_match('#' . $key . '#', $reqStr))
						{
							$reqStr = preg_replace('#' . $key . '#', $value, $reqStr);
							break;
						}
					}
				}
			}

			// convert uri into array
			$reqArr = explode('/', $reqStr);
			unset($reqStr);

			// first two segments is controller/action
			RcPHP::$_controller = empty($reqArr['0']) ? DEFAULT_CONTROLLER : $reqArr['0'];
			RcPHP::$_action = empty($reqArr['1']) ? DEFAULT_ACTION : $reqArr['1'];

			// uri parameters
			for($i = 2; $len = count($reqArr), $i < $len; $i++)
			{
				$f = $i % 2;
				if($f == 0)
				{
					$_GET[$reqArr[$i]] = RcPHP::$_params[$reqArr[$i]] = empty($reqArr[$i + 1]) ? null : $reqArr[$i + 1];
				}
			}
		}

		if(empty(RcPHP::$_controller) && empty(RcPHP::$_action) && !empty($_GET['r']))
		{
			$r = $_GET['r'];

			$tmp = explode("/", $r);

			RcPHP::$_controller = empty($tmp['0']) ? DEFAULT_CONTROLLER : $tmp['0'];
			RcPHP::$_action = empty($tmp['1']) ? DEFAULT_ACTION : $tmp['1'];

			unset($_GET['r']);
			unset($tmp);
		}

		RcPHP::$_controller = empty(RcPHP::$_controller) ? DEFAULT_CONTROLLER : RcPHP::$_controller;
		RcPHP::$_action = empty(RcPHP::$_action) ? DEFAULT_ACTION : RcPHP::$_action;

		$queryString = Request::header("QUERY_STRING");
		if($queryString !== false && !empty($queryString))
		{
			$querySplitArr = explode("&amp;", $queryString);
			foreach($querySplitArr as $k => $v)
			{
				$queryArr = explode("=", $v);
				for($i = 0; $len = count($queryArr), $i < $len; $i += 2)
				{
					$_GET[$queryArr[$i]] = RcPHP::$_params[$queryArr[$i]] = !isset($queryArr[$i + 1]) ? '' : urldecode($queryArr[$i + 1]);
				}
			}
		}
	}

	/**
	 * Route for client.
	 *
	 * @return void
	 */
	private static function client()
	{
		$argv = Request::header("argv", false);
		unset($argv[0]);

		if(empty($argv))
		{
			RcPHP::$_controller = DEFAULT_CONTROLLER;
			RcPHP::$_action = DEFAULT_ACTION;
		}
		else
		{
			RcPHP::$_controller = (!empty($argv[1])) ? strtolower($argv[1]) : DEFAULT_CONTROLLER;
			RcPHP::$_action = (!empty($argv[2])) ? strtolower($argv[2]) : DEFAULT_CONTROLLER;

			if(($totalNum = sizeof($argv)) > 3)
			{
				for($i = 3; $i < $totalNum; $i++)
				{
					if(substr($argv[$i], 0, 1) == '-')
					{
						$pos = strpos($argv[$i], '=');
						if($pos !== false)
						{
							$key = substr($argv[$i], 2, $pos - 2);
							RcPHP::$_params[$key] = substr($_SERVER['argv'][$i], $pos + 1);
							unset($argv[$i]);
						}
					}
				}
			}
		}
	}
}